package com.recource.controller;

import com.recource.dao.UserDao;
import com.recource.domain.Users;
import com.recource.ro.UserRO;
import com.recource.type.UserType;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.UUID;

/**
 *
 */
@Controller
public class LoginController {

    @Autowired
    private UserDao userDao;

    @RequestMapping("/login.html")
    public String loginHtml(){
        return "/login/login";
    }

    @RequestMapping("/login")
    //登录接口
    public ModelAndView login(UserRO ro, HttpServletRequest request, HttpServletResponse response){
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<Users>();
        wrapper.eq(Users::getUsername, ro.getUsername());
        //查找当前用户是否村子啊
        Users users = userDao.selectOne(wrapper);
        ModelAndView modelAndView = new ModelAndView();
        if(users == null){
            //如果用户不存在
            //跳转登录界面
            modelAndView.setViewName("/login/login");
            modelAndView.addObject("msg","用户不存在");
            return modelAndView;
        }
        if(users.getIndex() == 0){
            modelAndView.setViewName("/login/login");
            modelAndView.addObject("msg","用户未审核通过");
            return modelAndView;
        }
        String salt = users.getSalt();
        StringBuilder sb = new StringBuilder();
        try {
            String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
            if(!StringUtils.equals(password, users.getPassword())){
                //校验密码是否正确如果正确进入主页面
                modelAndView.setViewName("/login/login");
                modelAndView.addObject("msg","密码错误");
                return modelAndView;
            }
            //将登录成功的数据保存进session中
            String sessionId=  UUID.randomUUID().toString();
            request.getSession().setAttribute(sessionId, users);
            Cookie cookie = new Cookie("token", sessionId);
            cookie.setPath(request.getContextPath());
            if(StringUtils.equals(ro.getRemember(), "remember-me")){
                cookie.setMaxAge(90*9000);
            }else{
                cookie.setMaxAge(90*90);
            }
            //将sessionId保存到页面的cookie信息中方便进行校验信息
            response.addCookie(cookie);
            modelAndView.setViewName("redirect:/admin/index");
            return modelAndView;
        } catch (Exception e) {
            throw new RuntimeException("密码错误");
        }
    }

    @RequestMapping("/logout")
    //登出
    public ModelAndView loginout(HttpServletResponse response, HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("redirect:/login.html");
        request.getSession().invalidate();
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if(StringUtils.equals(cookie.getName(), "token")){
                //将当前的cookie清空
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }
        return modelAndView;
    }

    //跳转到注册的页面
    @RequestMapping("/register.html")
    public String registerHtml(UserRO ro){
        return "/login/register";
    }

    //注册方法
    @RequestMapping("/register")
    public ModelAndView register(Users ro){
        ModelAndView modelAndView = new ModelAndView();
        Users users = new Users();
        LambdaQueryWrapper<Users> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Users::getUsername, ro.getUsername());
        //查找当前用户
        Users users1 = userDao.selectOne(wrapper);
        //如果当前用户已经存在
        if(users1 != null){
            //跳转注册页面
            modelAndView.setViewName("/login/register");
            modelAndView.addObject("msg","当前用户名已经存在");
            return modelAndView;
        }
        //将注册信息注入数据库
        BeanUtils.copyProperties(ro, users);
        String salt = UUID.randomUUID().toString().substring(0, 5);
        users.setSalt(salt);
        StringBuilder sb = new StringBuilder();
        //保存密码并且加密
        String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
        users.setPassword(password);
        users.setUserType(UserType.SIMPLE.getIndex());
        users.setIndex(0);
        //新增用户到数据库中
        userDao.insert(users);
        //跳转到登录页面
        modelAndView.setViewName("/login/login");
        modelAndView.addObject("msg","注册成功，请登录");
        return modelAndView;
    }

    @RequestMapping("/forget.html")
    public String forget(){
        return "/login/forget";
    }

    //忘记密码
    @RequestMapping("/forget")
    public String forgetsss(UserRO ro){
        LambdaQueryWrapper<Users> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查找当前用户是否存在
        Users users = userDao.selectOne(objectLambdaQueryWrapper.eq(Users::getUsername, ro.getUsername()));
        if(Objects.nonNull(users)){
            //如果用户存在，更新用户的密码
            String salt = users.getSalt();
            StringBuilder sb = new StringBuilder();
            try {
                String password = DigestUtils.md5DigestAsHex((sb.append(salt).append(ro.getPassword())).toString().getBytes());
                users.setPassword(password);
                userDao.updateById(users);
            }catch (Exception e){
                e.printStackTrace();
            }
            //更新成功跳转登录页面
            return "/login/login";
        }
        //不存在就跳转忘记密码页面
        return "/login/forget";
    }

}